<?php

namespace app\admin\controller\system;

use think\App;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\facade\Db;
use think\response\Json;
use app\Request;
use think\facade\Log;
use app\common\controller\AdminController;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;

#[ControllerAnnotation(title: '字典选项')]
class DictionaryOption extends AdminController
{
    private array $notes;

    private array $rule = [
        'pid'   => 'require',
        'name'   => 'require',
        'value'   => 'require',
    ];
    private array $message = [
        'pid.require'   => '请输入【父级不能为空】',
        'name.require'   => '请输入【选项名称】',
        'value.require'   => '请输入【选项值】',
    ];

    #[NodeAnnotation(ignore: ['modify', 'recycle'])] // 过滤不需要生成的权限节点
    protected array $ignoreNode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        self::$model = new \app\admin\model\SystemDictionaryOption();
        $notes = self::$model::$notes;

        $this->notes = $notes;
        $this->assign(compact('notes'));
    }

    #[NodeAnnotation(title: '列表', auth: true)]
    public function index(Request $request, $id = 0): Json|string {
        if ($request->isAjax()) {

            [$page, $limit, $where, $excludeFields] = $this->buildTableParams();
            $model = (new self::$model)->where($where);
            try {
                $count = $model->count();
                $list  = $model->page($page,$limit)->order($this->sort)->select();
            } catch (PDOException | DbException $exception) {
                $count = 0;
                $list  = [];
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('id',$id);
        return $this->fetch();
    }

    #[NodeAnnotation(title: '添加', auth: true)]
    public function add(Request $request, $id = 0): string
    {
        $id = $request->param('pid');
        if ($id <= 0) {
            $this->error("父级ID错误");
        }

        if ($request->isPost()) {
            $post = $request->post();
            $this->validate($post, $this->rule, $this->message);
            try {
                $save = self::$model::create($post);
            }catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                
                $this->success('保存成功');
            }else {
                $this->error('保存失败');
            }
        }
        $this->assign('pid', $id);
        return $this->fetch();
    }
}
